﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using PhotoGallery.Modules.Authority.Model;
using PhotoGallery.Core.Business;
using PhotoGallery.Infrastructure.Helpers;
using System.Web.Script.Serialization;

namespace PhotoGallery.Modules.Authority.Controllers
{
    public class AccountRoleController : Controller
    {

        #region Field  & Property


        #endregion

        #region Constructor

        #endregion

        #region 操作

        /// <summary>
        /// 首页操作
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Index(AccountRoleSearch search)
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }


            if (search == null)
                search = new AccountRoleSearch();
            AccountRoleIndexModel model = new AccountRoleIndexModel(search, Core.Business.Account.Search(new AccountSearch() { Name = search.Name, Gender = search.Gender != null ? (Core.Business.Gender)search.Gender.Value : Core.Business.Gender.NotGiven, PageIndex = 1, PageSize = 100 }).Accounts);
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Edit(int? id)
        {
            if (id == null || !id.HasValue)
            {
                TempData["HintMessage"] = new HintMessage { Content = string.Format("请确认用户是否存在") };
                return RedirectToAction("Index");
            }

            Core.Business.Account account = Core.Business.Account.Load(id.Value);

            if (account == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = string.Format("请确认用户是否存在") };
                return RedirectToAction("Index");
            }

            AccountRoleEditModel model = new AccountRoleEditModel();

            model.Account = account;

            model.Roles = Role.GetAllRoles().Where(item => item.Status == 0).ToList().ToHashSet();

            model.Operations = new HashSet<Operation>();

            if (model.Account.Roles != null)
            {
                foreach (var role in model.Account.Roles)
                {
                    model.Operations = model.Operations.Union(role.Operations).ToHashSet();
                }
            }
            return View(model);
        }


        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityJsonFilterAttribute(Order = 1)]
        public JsonResult UpdateAccountRoles(int id, string strRoleids)
        {
            Core.Business.Account account = Core.Business.Account.Load(id);
            if (account == null)
                return Json(new { success = false, message = "系统发生错误，请检查要更新的帐号！" });

            if (strRoleids == null)
                return Json(new { success = false, message = "系统发生错误，请确认要添加的角色！" });

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            IList<int> roleids = serializer.Deserialize<IList<int>>(strRoleids);

            HashSet<Role> existRoles = account.Roles.ToHashSet();

            foreach (var roleid in roleids)
            {
                Role role = Role.Load(roleid);
                if (role == null)
                    continue;
                AccountRole accountRole = AccountRole.Load(new AccountRoleKey() { AccountId = account.Id, RoleId = role.Id });
                if (accountRole == null)
                {
                    accountRole = new AccountRole();
                    accountRole.Id = new AccountRoleKey() { AccountId = account.Id, RoleId = role.Id };
                    accountRole.Status = 0;
                    accountRole.Save();
                }
                else
                {
                    existRoles.Remove(role);
                }
            }

            foreach (var role in existRoles)
            {
                AccountRole accountRole = AccountRole.Load(new AccountRoleKey() { AccountId = account.Id, RoleId = role.Id });
                accountRole.DeleteOnSave();
                accountRole.Save();
            }

            return Json(new { success = true, message = "成功更新角色的信息！" }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
